<?php

/**
 * Get all groups
 * 
 * @global ezSQL_mysql $db 
 */
function getGroup() {
    global $dbna;

    $query = "SELECT * FROM groups";
    $groups = $dbna->get_results($query);

    if (!empty($groups)) {
        return $groups;
    } else {
        return false;
    }
}

/**
 * Get group list
 * 
 * @return string select html
 */
function groupSelect($selected = null) {
    $groups = getGroup();
    if ($groups) {
        $option = '';
        foreach ($groups as $g) {
            if ($selected == $g->id) {
                $option .= sprintf('<option value="%d" selected>%s</option>', $g->id, $g->name);
            } else {
                $option .= sprintf('<option value="%d">%s</option>', $g->id, $g->name);
            }
        }
        $select = sprintf('<select id="groups" name="groups">%s</select>', $option);
        return $select;
    }
    return false;
}

/**
 * USER MANAGEMENT
 */

/**
 * Save new user
 * 
 * @global ezSQL_mysql $dbna
 */
function save_new_user() {
    global $dbna;
    $username = $dbna->escape($_POST['username']);
    $password = md5($_POST['password']);
    $email = $dbna->escape($_POST['email']);
    $firstname = $dbna->escape($_POST['firstname']);
    $lastname = $dbna->escape($_POST['lastname']);
    $group_id = $_POST['groups'];
    $created = date('Y-m-d');

    $query = "INSERT INTO users(username, password, email, firstname, lastname, created, group_id) 
                  VALUES('$username', '$password', '$email', '$firstname', '$lastname','$created', $group_id)";

    if ($dbna->query($query)) {
        echo 'Insert success';
    } else {
        echo 'Insert fail';
    }
}

function update_user() {
    global $dbna;
    $errorMsg = false;
    $isChangePassword = false;

    $password = isset($_POST['password']) ? $_POST['password'] : '';
    $passwordconfirm = isset($_POST['newpwd']) ? $_POST['newpwd'] : '';

    $email = isset($_POST['email']) ? $dbna->escape($_POST['email']) : '';
    $firstname = isset($_POST['firstname']) ? $dbna->escape($_POST['firstname']) : '';
    $lastname = isset($_POST['lastname']) ? $dbna->escape($_POST['lastname']) : '';
    $group_id = $_POST['groups'];

    if (($password != '' && $passwordconfirm != '')) {

        if (($password == $passwordconfirm)) {
            $set = "email= '$email',password = '" . md5($password) . "', firstname= '$firstname',lastname = '$lastname', group_id = $group_id";
            $isChangePassword = true;
        } else {
            $errorMsg = 'Password not match!';
        }
    }
    if ($errorMsg == false) {
        if (!$isChangePassword) {
            $set = "email= '$email', firstname= '$firstname',lastname = '$lastname', group_id = $group_id";
        }
        //$created = date('Y-m-d');
        $user_id = $_POST['user_id'];
        $query = "UPDATE users
					 SET  $set
					 WHERE id  = $user_id";

        if ($dbna->query($query)) {
            $_SESSION['msg'] = 'Update success';
            redirect(admin_url() . '/user.php');
        } else {
            echo 'Uppdate fail';
        }
    } else {
        echo $errorMsg;
    }
}

function delete_user($user_id) {
    global $dbna;
    $dbna->query("DELETE FROM users WHERE id = $user_id");
}

/**
 * Chechk login amdin
 * 
 */
function checkLogin() {
    if (!isLogin()) {
        redirect(BASE_URL . 'login.php');
        exit;
    }
}

function isLogin() {
    if (isset($_SESSION['login_user_identify']))
        return true;
    else
        return false;
}

/**
 * Redirect Function
 *
 */
function redirect($url, $permanent = false) {
    if ($permanent) {
        header('HTTP/1.1 301 Moved Permanently');
    }
    header('Location: ' . $url);
    exit();
}

/**
 * User logon
 *
 */
function user_logon() {
    global $dbna;
    // if we found an error save the error message in this variable
    $errorMessage = '';

    $username = isset($_POST['username']) ? $dbna->escape($_POST['username']) : false;
    $password = isset($_POST['password']) ? $_POST['password'] : false;

    if ($username == '') {
        $errorMessage = 'You must enter your username';
    } else if ($password == '') {
        $errorMessage = 'You must enter the password';
    } else {

        $query = "SELECT * FROM users WHERE username = '$username' AND password='" . md5($password) . "'";
        $user = $dbna->get_row($query);
        if (!empty($user)) {
            $_SESSION['login_user_identify'] = 1;
            $_SESSION['current_user'] = $user;
            return true;
        } else {
            $errorMessage = 'Wrong username or password';
        }
    }

    $_SESSION['errorMessage'] = $errorMessage;
    return false;
}

/**
 * Logout function
 *
 *
 */
function doLogout() {
    if (isset($_SESSION['login_user_identify'])) {
        unset($_SESSION['login_user_identify']);
        session_unregister('login_user_identify');
        redirect(BASE_URL . '/login.php');
    }
}

/**
 * Function admin_url
 *
 */
function admin_url($uri = null) {
    if ($uri)
        return BASE_URL . 'admin/' . $uri;

    return BASE_URL . 'admin';
}

/** Save new client * */
function save_new_client() {
    global $dbna;
    $company_name = $dbna->escape($_POST['company_name']);
    $address = $dbna->escape($_POST['address']);
    $phone = $dbna->escape($_POST['phone']);
    $fax = $dbna->escape($_POST['fax']);
    $country = $dbna->escape($_POST['country']);
    $zip_code = $dbna->escape($_POST['zip_code']);

    $query = "INSERT INTO clients(company_name, address, phone, fax, country, zip_code) VALUES('$company_name', '$address', '$phone', '$fax', '$country', '$zip_code')";

    if ($dbna->query($query)) {
        redirect(BASE_URL . 'admin/client.php');
        
    } else {
        
    }
}

/* * edit clients* */

function update_clients() {
    global $dbna;
    $company_name = $dbna->escape($_POST['company_name']);
    $address = $dbna->escape($_POST['address']);
    $phone = $dbna->escape($_POST['phone']);
    $fax = $dbna->escape($_POST['fax']);
    $country = $dbna->escape($_POST['country']);
    $zip_code = $dbna->escape($_POST['zip_code']);

    $query = "UPDATE clients 
                  SET company_name='$company_name',address='$address',phone='$phone',fax='$fax',country='$country',zip_code='$zip_code'
                  WHERE id  = $id";
    
    //echo $query;
    if ($dbna->query($query)) {
        redirect(BASE_URL . 'admin/client.php');
        echo 'Update success';
    } else {
        echo 'Update fail';
    }
}

/* * delete clients* */

function delete_clients() {
    global $dbna;
    $id = $_GET['client_id'];
    $dbna->query("DELETE FROM clients WHERE id = $id");
    redirect(admin_url() . '/client.php');
}

function edit_clients($client_id) {
    global $dbna;
    $dbna->query("Edite FROM clients WHERE id = $client_id");
    redirect(admin_url() . '/client.php');
}



/**
  save shipper-add
 * */
function save_shipper() {
    global $dbna;
    $sender_name = $dbna->escape($_POST['sender_name']);
    $address = $dbna->escape($_POST['address']);
    $sent = $dbna->escape($_POST['sent']);
    $receive_name = $dbna->escape($_POST['receive_name']);
    $received = $dbna->escape($_POST['received']);
    $phone = $dbna->escape($_POST['phone']);
    $fax = $dbna->escape($_POST['fax']);
    $country = $dbna->escape($_POST['country']);
    $zip = $dbna->escape($_POST['zip']);

    $query = "INSERT INTO shippers(sender_name,address, sent, receive_name, received, phone, fax, country, zip) 
                  VALUES('$sender_name', '$address', '$sent', '$receive_name', '$received', '$phone', '$fax', '$country', '$zip')";

    if ($dbna->query($query)) {
        redirect(BASE_URL . 'admin/shipper.php');
        echo 'Insert success';
    } else {
        echo 'Insert fail';
    }
}
/* * update shipper* */
function update_shippers() {
    global $dbna;
    
    $id = $_POST['shipper_id'];
    $sender_name = $dbna->escape($_POST['sender_name']);
    $address = $dbna->escape($_POST['address']);
    $sent = $dbna->escape($_POST['sent']);
    $receive_name = $dbna->escape($_POST['receive_name']);
    $receive_date = $dbna->escape($_POST['receive_date']);
    $phone = $dbna->escape($_POST['phone']);
    $fax = $dbna->escape($_POST['fax']);
    $country = $dbna->escape($_POST['country']);
    $zip = $dbna->escape($_POST['zip']);

      $query = "UPDATE shippers 
            SET sender_name = '$sender_name', address = '$address', sent = '$sent', receive_name = '$receive_name', 
            receive_date = '$receive_date', phone = '$phone', country = '$country', zip = '$zip'
            WHERE id  = $id";
    //echo $query;

    if ($dbna->query($query)) {
        echo 'Update success';
        redirect(BASE_URL . 'admin/shipper.php');
    } else {
        echo 'Update fail';
    }
}

/* * delete shipper* */

function delete_shipper() {
    global $dbna;
    $id = $_GET['shippers_id'];
    $dbna->query("DELETE FROM shippers WHERE id = $id");
    redirect(admin_url() . '/shipper.php');
}

function edit_shippers($shippers_id) {
    global $dbna;
    $dbna->query("Edite FROM shippers WHERE id = $shippers_id");
    redirect(admin_url() . '/shipper.php');
}

/** Save shipment detail * */
function save_shipment_detail() {
    global $dbna;
    $origin = $dbna->escape($_POST['origin']);
    $weight = md5($_POST['weight']);
    $decription = $_POST['description'];
    $pieces = $dbna->escape($_POST['pieces']);
    $payment = $dbna->escape($_POST['payment']);
    $payment_type = $dbna->escape($_POST['payment_type']);

    $query = "INSERT INTO shipment_detail(origin, weight, price, decription, pieces,payment, payment_type) 
                  VALUES('$origin', '$weight','$price', '$decription', '$pieces', '$payment','$payment_type')";

    if ($dbna->query($query)) {
        echo 'Insert success';
        redirect(BASE_URL . 'admin/shipment-detail.php');
    } else {
        echo 'Insert fail';
    }
}

function update_shipment_detail() {
    global $dbna;
    $id = $dbna->escape($_POST['shipment_id']);
    $origin = $dbna->escape($_POST['origin']);
    $weight = md5($_POST['weight']);
    $price = $dbna->escape($_POST['price']);
    $decription = $_POST['description'];
    $pieces = $dbna->escape($_POST['pieces']);
    $payment = $dbna->escape($_POST['payment']);
    $payment_type = $dbna->escape($_POST['payment_type']);

    $query = "UPDATE shipment_detail 
            SET origin = '$origin', weight = '$weight', price ='$price', decription = '$decription', 
            pieces = '$pieces', payment = '$payment', payment_type = '$payment_type'
            WHERE id = $id";

    if ($dbna->query($query)) {
        echo 'Update success';
        redirect(BASE_URL . 'admin/shipment-detail.php');
    } else {
        echo 'Update fail';
    }
}
/**
  save consignee-add
 * */
function save_consignee() {
    global $dbna;
    $receive_name = $dbna->escape($_POST['receivename']);
    $phone = $dbna->escape($_POST['phone']);
    $fax = $dbna->escape($_POST['fax']);
    $country = $dbna->escape($_POST['country']);
    $zip = $dbna->escape($_POST['zip']);

    $query = "INSERT INTO consignee(receive_name, phone, fax, country, zip) 
                  VALUES('$receive_name', '$phone', '$fax', '$country', '$zip')";

    if ($dbna->query($query)) {
        //echo 'Insert success';
        redirect(BASE_URL . 'admin/consignee.php');
    } else {
        //echo 'Insert fail';
    }
}

/* * edit consignee* */

function update_consignee() {
    global $dbna;
    $receive_name = $dbna->escape($_POST['receive_name']);
    $phone = $dbna->escape($_POST['phone']);
    $fax = $dbna->escape($_POST['fax']);
    $country = $dbna->escape($_POST['country']);
    $zip = $dbna->escape($_POST['zip']);
    $id = $_POST['consignee_id'];

    $query = "UPDATE consignee 
                  SET receive_name='$receive_name',phone='$phone',fax='$fax',country='$country',zip='$zip'
                  WHERE id  = $id";
    //echo $query;
    if ($dbna->query($query)) {
        redirect(BASE_URL . 'admin/consignee.php');
        // echo 'Update success';
    } else {
        // echo 'Update fail';
    }
}

/* * delete consignee* */

function delete_consignee() {
    global $dbna;
    $id = $_GET['consignee_id'];
    $dbna->query("DELETE FROM consignee WHERE id = $id");
    redirect(admin_url() . '/consignee.php');
}

function edit_consignee($consignee_id) {
    global $dbna;
    $dbna->query("Edite FROM consignee WHERE id = $consignee_id");
    redirect(admin_url() . '/consignee.php');
}

/** delect shipment detail.php * */
function delete_shipment_detail($shipment_id) {
    global $dbna;
    $dbna->query("DELETE FROM shipment_detail WHERE id = $shipment_id");
    redirect(admin_url() . '/shipment-detail.php');
}

function edit_shipment_detail($shipment_id) {
    global $dbna;
    $dbna->query("Edite FROM shipment_detail WHERE id = $shipment_id");
    redirect(admin_url() . '/shipment-detail.php');
}
function getCountries() {
    global $dbna;
    $countries = $dbna->get_results("SELECT * FROM country");
    return $countries; 
}
function countrySelect($selected = null ){
    $countries = getCountries();
    $options = '';
    foreach($countries as $c) {
        if ($c->id == $selected) {
            $options .= sprintf('<option value="%d" selected="selected">%s</option>', $c->id, $c->printable_name);
        } else {
            $options .= sprintf('<option value="%d">%s</option>', $c->id, $c->printable_name);
        }
        
    }
    return sprintf('<select name="country">%s</select>', $options);
}
/**
  save tracking
 * */
function save_tracking() {
    global $dbna;
    $bill_id = $dbna->escape($_POST['bill_id']);
    $shipped_on = $dbna->escape($_POST['shipped_on']);
    $destination = $dbna->escape($_POST['destination']);
    $delivered_date = $dbna->escape($_POST['delivered_date']);
    $description = $dbna->escape($_POST['description']);
    $detail_date = $dbna->escape($_POST['detail_date']);
    $location_id = $dbna->escape($_POST['location_id']);
    $sign_by = $dbna->escape($_POST['sign_by']);
    $status = $_POST['status_id'];
    $weight = $dbna->escape($_POST['weight']);
    $piece = $dbna->escape($_POST['piece']);

    $query = "INSERT INTO 
                tracking(bill_id, shipped_on, destination, delivered_date, description, detail_date,tracking_status_id, location_id, sign_by, weight, piece) 
                VALUES('$bill_id', '$shipped_on', '$destination', '$delivered_date', '$description', '$detail_date', $status,  '$location_id', '$sign_by', '$weight', '$piece')";
    
    if ($dbna->query($query)) {
        echo 'Insert success';
       redirect(BASE_URL . 'admin/tracking.php');
    } else {
        echo 'Insert fail';
    }
}
?>